package example;

import cn.hutool.core.lang.Console;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.mail.MailUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.qcloud.services.scf.runtime.events.APIGatewayProxyRequestEvent;
import example.dto.Backtrack;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 所属项目:emaliSend
 *
 * @author rui10038 邮箱：2450782689@qq.com
 * @version 1.0
 * //                .-~~~~~~~~~-._       _.-~~~~~~~~~-.
 * //            __.'              ~.   .~              `.__
 * //          .'//    JAVA无涯      \./     回头是岸     \\`.
 * //        .'//                     |                     \\`.
 * //      .'// .-~"""""""~~~~-._     |     _,-~~~~"""""""~-. \\`.
 * //    .'//.-"                 `-.  |  .-'                 "-.\\`.
 * //  .'//______.============-..   \ | /   ..-============.______\\`.
 * //.'______________________________\|/______________________________`.
 * @date 2020/11/21 -下午 4:43
 **/

public class Hello {
    public Hello() {
    }

    public JSONObject mainHandler(APIGatewayProxyRequestEvent event) {
        String sendTo;
        String title;
        String message;
        if (event.getHttpMethod().equals("POST")) {
            String body = event.getBody();
            JSONObject jsonObject = JSONUtil.parseObj(body);
            sendTo = jsonObject.getStr("sendTo");
            title = jsonObject.getStr("title");
            message = jsonObject.getStr("message");
        } else {
            Map<String, String> queryStringParameters = event.getQueryString();
            sendTo = queryStringParameters.get("sendTo");
            title = queryStringParameters.get("title");
            message = queryStringParameters.get("message");
        }
        if (StrUtil.isBlank(sendTo)) {
            sendTo = "zhangrui1029@foxmail.com";
        }
        if (StrUtil.isBlank(title)) {
            title = "项目报错了快起床！！！";
        }
        if (StrUtil.isBlank(message)) {
            message = "项目报错了快起床！！！";
        }
        Backtrack backtrack = new Backtrack();
        backtrack.setIsBase64Encoded(false);
        backtrack.setStatusCode(200);
        HashMap<String, String> stringStringHashMap = new HashMap<>();
        stringStringHashMap.put("Content-Type", "application/json");
        Console.log("发给谁{},标题{},信息{}", sendTo, title, message);
        try {
            MailUtil.send(sendTo, title, message, true);
            backtrack.setBody("{\"code\":200,\"result\":\"发送成功\"}");
        } catch (Exception e) {
            backtrack.setBody("{\"code\":500,\"result\":\"发送失败,嵌套异常为:" + e.toString() + "\"}");
            e.printStackTrace();
        }
        backtrack.setHeaders(stringStringHashMap);
        return JSONUtil.parseObj(backtrack, false, true);
    }
}
